package com.example.seabedmusic.presenter;

import static android.webkit.URLUtil.isValidUrl;

import android.content.Context;
import android.util.Log;

import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.ApiResult;
import com.example.seabedmusic.entity.Song;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MusicPresenter implements MusicContract.IMusicPresenter {

    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_FAIL    = 1;
    private static final int PAGE_SIZE = 20; // 每页大小

    private MusicContract.IMusicView mView;
    private Context mContext;
    private OkHttpClient mClient;
    private Gson mGson = new Gson();

    public MusicPresenter(MusicContract.IMusicView view, Context context) {
        mView = view;
        mContext = context;
        mClient = createUnsafeOkHttpClient();
        mGson = new Gson();
    }

    /**
     * 创建不验证SSL证书的OkHttpClient（仅用于开发环境）
     */
    private OkHttpClient createUnsafeOkHttpClient() {
        try {
            // 创建信任所有证书的TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            // 安装信任所有证书的SSLContext
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // 创建不验证主机名的SSLSocketFactory
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true); // 不验证主机名
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
            builder.writeTimeout(30, TimeUnit.SECONDS);

            return builder.build();
        } catch (Exception e) {
            Log.e("OkHttpClient", "创建不安全HTTP客户端失败，使用默认客户端", e);
            return new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
        }
    }

    /* --------------------- 5 个独立接口 --------------------- */

    /**
     * 获取每日推荐 - 使用酷狗音乐每日推荐API
     */
    @Override
    public void getDaily()  {
        // 使用酷狗音乐每日推荐API，rankid=8888 是酷狗音乐的每日推荐榜单
        int page = 1; // 第一页
        String url = "https://m.kugou.com/rank/info/?rankid=8888&page=" + page + "&json=true&pagesize=" + PAGE_SIZE;

        mView.showLoading();
        Request req = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .build();

        mClient.newCall(req).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("服务器异常");
                    });
                    return;
                }
                try {
                    String responseData = response.body().string();
                    Log.d("DAILY_API", "每日推荐API响应: " + responseData);

                    List<Song> songs = parseKugouDailyResponse(responseData);

                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        if (songs.isEmpty()) {
                            mView.showToast("暂无每日推荐歌曲");
                        } else {
                            mView.showSongs(songs);
                        }
                    });
                } catch (Exception e) {
                    Log.e("DAILY_API", "解析每日推荐数据失败: " + e.getMessage());
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("解析每日推荐失败");
                    });
                }
            }
        });
    }

    /**
     * 解析酷狗每日推荐API返回的JSON数据
     */
    private List<Song> parseKugouDailyResponse(String rawResponse) throws JSONException {
        List<Song> songs = new ArrayList<>();

        Log.d("DAILY_PARSE", "开始解析每日推荐响应，长度: " + rawResponse.length());

        JSONObject jsonResponse = new JSONObject(rawResponse);
        Log.d("DAILY_PARSE", "JSON对象创建成功");

        // 酷狗API的数据结构：直接包含songs字段
        if (jsonResponse.has("songs")) {
            JSONObject songsData = jsonResponse.getJSONObject("songs");
            Log.d("DAILY_PARSE", "找到songs对象");

            if (songsData.has("list")) {
                JSONArray songsList = songsData.getJSONArray("list");
                Log.d("DAILY_PARSE", "找到songs list数组，长度: " + songsList.length());

                for (int i = 0; i < songsList.length(); i++) {
                    JSONObject songJson = songsList.getJSONObject(i);

                    // 直接创建Song对象
                    Song song = new Song();

                    // 设置ID - 使用hash作为ID
                    String songHash = "";
                    if (songJson.has("hash")) {
                        songHash = songJson.getString("hash");
                        song.setId(songHash);
                    }

                    // 设置标题
                    if (songJson.has("songname")) {
                        song.setTitle(songJson.getString("songname"));
                    } else {
                        song.setTitle("未知歌曲");
                    }

                    // 设置艺术家 - 从authors数组中获取
                    if (songJson.has("authors")) {
                        JSONArray authors = songJson.getJSONArray("authors");
                        if (authors.length() > 0) {
                            JSONObject author = authors.getJSONObject(0);
                            if (author.has("author_name")) {
                                song.setArtist(author.getString("author_name"));
                            } else {
                                song.setArtist("未知歌手");
                            }
                        } else {
                            song.setArtist("未知歌手");
                        }
                    } else {
                        song.setArtist("未知歌手");
                    }

                    // 设置专辑
                    if (songJson.has("album_name")) {
                        song.setAlbum(songJson.getString("album_name"));
                    } else if (songJson.has("album_id")) {
                        song.setAlbum("专辑ID: " + songJson.getString("album_id"));
                    }

                    // 设置封面 - 使用album_sizable_cover字段
                    if (songJson.has("album_sizable_cover")) {
                        String albumCover = songJson.getString("album_sizable_cover");
                        if (albumCover != null && !albumCover.isEmpty()) {
                            // 处理封面URL，替换{size}为实际尺寸
                            albumCover = albumCover.replace("{size}", "150");
                            if (albumCover.startsWith("//")) {
                                albumCover = "https:" + albumCover;
                            } else if (!albumCover.startsWith("http")) {
                                albumCover = "https://" + albumCover;
                            }
                            song.setCover(albumCover);
                        }
                    }

                    // 设置占位符URL，实际播放时再获取真实链接
                    song.setUrl("kugou_hash:" + songHash);

                    // 设置时长
                    if (songJson.has("duration")) {
                        try {
                            song.setDuration(songJson.getLong("duration") * 1000); // 转换为毫秒
                        } catch (JSONException e) {
                            song.setDuration(0);
                        }
                    }

                    songs.add(song);
                    Log.d("DAILY_SONG", "添加每日推荐歌曲: " + song.getTitle() + " - " + song.getArtist());
                    Log.d("DAILY_SONG", "歌曲Hash: " + songHash);
                }
            } else {
                Log.e("DAILY_PARSE", "songs中没有list字段");
            }
        } else {
            Log.e("DAILY_PARSE", "响应中没有songs字段");
        }

        return songs;
    }

    @Override public void getFav()    { request("/fav.json"); }
    @Override public void getHot()    { request("/hot.json"); }
    @Override public void getRandom() { request("/random.json"); }

    @Override
    public void getRecent() {
        mView.showLoading();
        HttpUrl url = HttpUrl.parse("https://music.example.com/recent.json");
        Request req = new Request.Builder().url(url).build();
        mClient.newCall(req).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();
                });
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("服务器异常");
                    });
                    return;
                }
                try {
                    Type type = new TypeToken<ApiResult<List<Song>>>(){}.getType();
                    ApiResult<List<Song>> ar = mGson.fromJson(response.body().string(), type);
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        if (ar.code == HTTP_SUCCESS) {
                            mView.showRecent(ar.data);
                        } else {
                            mView.showToast(ar.msg);
                        }
                    });
                } catch (Exception e) {
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("解析失败");
                    });
                }
            }
        });
    }

    /* -------------- 搜索：新接口 -------------- */
    @Override
    public void search(String key) {
        if (key == null || key.trim().isEmpty()) {
            mView.showToast("请输入关键字");
            return;
        }
        mView.showLoading();

        // 对关键词进行URL编码
        String encodedKey;
        try {
            encodedKey = java.net.URLEncoder.encode(key.trim(), "UTF-8");
        } catch (Exception e) {
            encodedKey = key.trim();
        }

        String url = "http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=" + encodedKey;
        Log.e("SEARCH_URL", "请求URL: " + url);

        Request req = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .build();

        mClient.newCall(req).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("NETWORK_ERROR", "网络请求失败: " + e.getMessage(), e);
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();
                    mView.showToast("网络错误: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("NETWORK_RESPONSE", "响应码: " + response.code());

                if (!response.isSuccessful()) {
                    Log.e("NETWORK_ERROR", "HTTP错误: " + response.code());
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("服务器异常: " + response.code());
                    });
                    return;
                }

                try {
                    String raw = response.body().string();
                    Log.d("RESPONSE_RAW", "响应内容: " + raw);

                    if (raw == null || raw.isEmpty()) {
                        throw new IOException("响应内容为空");
                    }

                    List<Song> list = parseKugouResponse(raw);
                    Log.d("PARSE_RESULT", "解析成功，歌曲数量: " + list.size());

                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        if (list.isEmpty()) {
                            mView.showToast("未找到相关歌曲");
                        } else {
                            mView.showSongs(list);
                        }
                    });
                } catch (Exception e) {
                    Log.e("PARSE_ERROR", "解析异常: " + e.getMessage(), e);
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("解析失败: " + e.getMessage());
                    });
                }
            }
        });
    }

    /**
     * 解析酷狗API返回的JSON数据
     */
    private List<Song> parseKugouResponse(String rawResponse) throws JSONException {
        List<Song> songs = new ArrayList<>();

        Log.d("PARSE_DEBUG", "开始解析响应，长度: " + rawResponse.length());

        JSONObject jsonResponse = new JSONObject(rawResponse);
        Log.d("PARSE_DEBUG", "JSON对象创建成功");

        // 检查状态码
        if (jsonResponse.has("status")) {
            int status = jsonResponse.getInt("status");
            Log.d("PARSE_DEBUG", "API状态码: " + status);
        }

        // 酷狗API的数据结构：data -> info 数组
        if (jsonResponse.has("data")) {
            JSONObject data = jsonResponse.getJSONObject("data");
            Log.d("PARSE_DEBUG", "找到data对象");

            if (data.has("info")) {
                JSONArray infoArray = data.getJSONArray("info");
                Log.d("PARSE_DEBUG", "找到info数组，长度: " + infoArray.length());

                for (int i = 0; i < infoArray.length(); i++) {
                    JSONObject songJson = infoArray.getJSONObject(i);

                    // 直接创建Song对象
                    Song song = new Song();

                    // 设置ID
                    if (songJson.has("hash")) {
                        song.setId(songJson.getString("hash"));
                    }

                    // 设置标题
                    if (songJson.has("songname")) {
                        song.setTitle(songJson.getString("songname"));
                    } else {
                        song.setTitle("未知歌曲");
                    }

                    // 设置艺术家
                    if (songJson.has("singername")) {
                        song.setArtist(songJson.getString("singername"));
                    } else {
                        song.setArtist("未知歌手");
                    }

                    // 设置封面
                    if (songJson.has("album_id")) {
                        String albumId = songJson.getString("album_id");
                        if (albumId != null && !albumId.isEmpty()) {
                            song.setCover("https://img1.kugou.com/album/" + albumId + ".jpg");
                        }
                    }

                    songs.add(song);
                    Log.d("PARSE_SONG", "添加歌曲: " + song.getTitle() + " - " + song.getArtist());
                }
            } else {
                Log.e("PARSE_DEBUG", "data中没有info字段");
            }
        } else {
            Log.e("PARSE_DEBUG", "响应中没有data字段");
        }

        return songs;
    }

    /* 通用请求主列表 */
    private void request(String path) {
        mView.showLoading();
        HttpUrl url = HttpUrl.parse("https://music.example.com" + path);
        Request req = new Request.Builder().url(url).build();
        mClient.newCall(req).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();

                });
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("服务器异常");
                    });
                    return;
                }
                try {
                    Type type = new TypeToken<ApiResult<List<Song>>>(){}.getType();
                    ApiResult<List<Song>> ar = mGson.fromJson(response.body().string(), type);
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        if (ar.code == HTTP_SUCCESS) {
                            mView.showSongs(ar.data);
                        } else {
                            mView.showToast(ar.msg);
                        }
                    });
                } catch (Exception e) {
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("解析失败");
                    });
                }
            }
        });
    }

    /**
     * 获取随机音乐 - 使用新的网易云热歌API
     */
    @Override
    public void getRandomMusic() {
        android.util.Log.d("MusicPresenter", "开始获取随机音乐");
        mView.showLoading();

        // 使用新的网易云热歌API
        String apiUrl = "https://api.zxki.cn/api/wyyrg";

        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .addHeader("Accept", "application/json")
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                android.util.Log.e("RANDOM_MUSIC", "网易云热歌API请求失败: " + e.getMessage());
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();
                    mView.showToast("网络异常，请稍后重试");
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    android.util.Log.d("RANDOM_MUSIC", "网易云热歌API响应码: " + response.code());

                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        android.util.Log.d("RANDOM_MUSIC", "完整API响应: " + responseData);

                        if (responseData != null && !responseData.isEmpty()) {
                            handleWyyrgApiResponse(responseData);
                        } else {
                            throw new IOException("响应数据为空");
                        }
                    } else {
                        // 记录详细的HTTP错误信息
                        String errorBody = response.body().string();
                        android.util.Log.e("RANDOM_MUSIC", "HTTP错误，响应体: " + errorBody);
                        throw new IOException("HTTP错误: " + response.code() + ", 响应: " + errorBody);
                    }
                } catch (Exception e) {
                    android.util.Log.e("RANDOM_MUSIC", "处理网易云热歌API响应失败: " + e.getMessage());
                    ((android.app.Activity) mContext).runOnUiThread(() -> {
                        mView.hideLoading();
                        mView.showToast("获取随机音乐失败: " + e.getMessage());
                    });
                }
            }
        });
    }

    @Override
    public void getHotSongs() {
        // 调用热歌榜API
        getHot();
    }

    /**
     * 处理网易云热歌API的响应
     */
    private void handleWyyrgApiResponse(String responseData) {
        try {
            android.util.Log.d("WYYRG_API", "开始解析网易云热歌API响应");
            android.util.Log.d("WYYRG_API", "原始响应数据: " + responseData);

            JSONObject jsonResponse = new JSONObject(responseData);

            // 打印所有顶级字段
            java.util.Iterator<String> topKeys = jsonResponse.keys();
            android.util.Log.d("WYYRG_API", "顶级字段:");
            while (topKeys.hasNext()) {
                String key = topKeys.next();
                android.util.Log.d("WYYRG_API", "  " + key + ": " + jsonResponse.opt(key));
            }

            // 检查API返回状态 - 尝试多种可能的成功码
            int code = jsonResponse.optInt("code", -1);
            int status = jsonResponse.optInt("status", -1);

            // 如果code不是200，检查status
            if (code == 200 || status == 200 || code == 1 || status == 1) {
                // 尝试获取data字段，可能是对象或数组
                Object dataObj = jsonResponse.opt("data");

                if (dataObj instanceof JSONObject) {
                    // data是对象
                    JSONObject data = (JSONObject) dataObj;
                    parseSongFromData(data);
                } else if (dataObj instanceof JSONArray) {
                    // data是数组，取第一个
                    JSONArray dataArray = (JSONArray) dataObj;
                    if (dataArray.length() > 0) {
                        JSONObject data = dataArray.getJSONObject(0);
                        parseSongFromData(data);
                    } else {
                        throw new JSONException("data数组为空");
                    }
                } else if (dataObj != null) {
                    // data可能是其他类型，直接使用响应中的字段
                    parseSongFromData(jsonResponse);
                } else {
                    // 没有data字段，尝试直接从根对象解析
                    parseSongFromData(jsonResponse);
                }

            } else {
                // 获取详细的错误信息
                String errorMsg = jsonResponse.optString("msg",
                        jsonResponse.optString("message",
                                jsonResponse.optString("error", "API返回错误")));
                android.util.Log.e("WYYRG_API", "API返回错误 - code: " + code + ", status: " + status + ", msg: " + errorMsg);
                ((android.app.Activity) mContext).runOnUiThread(() -> {
                    mView.hideLoading();
                    mView.showToast("API错误: " + errorMsg + " (code: " + code + ")");
                });
            }

        } catch (JSONException e) {
            android.util.Log.e("WYYRG_API", "解析JSON失败: " + e.getMessage());
            android.util.Log.e("WYYRG_API", "响应数据: " + responseData);
            ((android.app.Activity) mContext).runOnUiThread(() -> {
                mView.hideLoading();
                mView.showToast("解析音乐数据失败");
            });
        } catch (Exception e) {
            android.util.Log.e("WYYRG_API", "处理网易云热歌数据异常: " + e.getMessage());
            ((android.app.Activity) mContext).runOnUiThread(() -> {
                mView.hideLoading();
                mView.showToast("处理音乐数据异常");
            });
        }
    }

    /**
     * 从数据对象解析歌曲信息
     */
    private void parseSongFromData(JSONObject data) throws JSONException {
        List<Song> songs = new ArrayList<>();
        Song song = new Song();

        // 打印所有可用字段用于调试
        java.util.Iterator<String> dataKeys = data.keys();
        android.util.Log.d("WYYRG_API", "数据字段:");
        while (dataKeys.hasNext()) {
            String key = dataKeys.next();
            android.util.Log.d("WYYRG_API", "  " + key + ": " + data.opt(key));
        }

        // 设置歌曲基本信息 - 尝试多种可能的字段名
        String[] titleFields = {"name", "title", "songName", "musicName"};
        String[] artistFields = {"artist", "singer", "author", "artistName", "singerName","artistsname"};
        String[] urlFields = {"url", "music_url", "audio", "audio_url", "play_url"};
        String[] coverFields = {"pic", "cover", "image", "picUrl", "coverUrl", "albumPic","pic_url","picurl"};
        String[] albumFields = {"album", "albumName","alname"};

        // 设置标题
        song.setTitle(getFieldValue(data, titleFields, "未知歌曲"));

        // 设置艺术家
        song.setArtist(getFieldValue(data, artistFields, "未知歌手"));

        // 设置专辑
        song.setAlbum(getFieldValue(data, albumFields, "未知专辑"));

        // 设置播放链接
        String playUrl = getFieldValue(data, urlFields, "").trim();
        android.util.Log.d("WYYRG_API", "原始播放链接: " + playUrl);

        // 处理播放链接
        if (playUrl != null && !playUrl.isEmpty()) {
            // 如果URL不是以http开头，添加https前缀
            if (!playUrl.startsWith("http")) {
                if (playUrl.startsWith("//")) {
                    playUrl = "https:" + playUrl;
                } else {
                    playUrl = "https://" + playUrl;
                }
            }

            // 验证URL格式
            if (isValidUrl(playUrl)) {
                song.setUrl(playUrl);
                android.util.Log.d("WYYRG_API", "处理后的播放链接: " + playUrl);
            } else {
                android.util.Log.e("WYYRG_API", "无效的URL格式: " + playUrl);
                playUrl = "";
            }
        } else {
            android.util.Log.w("WYYRG_API", "播放链接为空");
            playUrl = "";
        }

        // 设置封面图片
        String coverUrl = getFieldValue(data, coverFields, "");
        if (coverUrl != null && !coverUrl.isEmpty()) {
            if (!coverUrl.startsWith("http")) {
                if (coverUrl.startsWith("//")) {
                    coverUrl = "https:" + coverUrl;
                } else {
                    coverUrl = "https://" + coverUrl;
                }
            }
            song.setCover(coverUrl);
            android.util.Log.d("WYYRG_API", "封面链接: " + coverUrl);
        }else {
            // 如果没有封面URL，可以设置一个默认封面
            song.setCover("");
            android.util.Log.w("WYYRG_API", "未找到封面链接");
        }

        // 设置歌词
        String[] lyricFields = {"lrc", "lyric", "lyrics"};
        String lyrics = getFieldValue(data, lyricFields, "");
        if (!lyrics.isEmpty()) {
            song.setLyrics(lyrics);
        }

        // 设置ID
        song.setId(String.valueOf(System.currentTimeMillis()));

        songs.add(song);

        android.util.Log.d("WYYRG_API", "成功解析歌曲: " + song.getTitle() + " - " + song.getArtist());
        android.util.Log.d("WYYRG_API", "播放链接: " + song.getUrl());
        android.util.Log.d("WYYRG_API", "封面链接: " + song.getCover());

        // 创建final变量用于lambda表达式
        final String finalPlayUrl = playUrl;
        final String finalSongTitle = song.getTitle();
        final String finalSongArtist = song.getArtist();
        final List<Song> finalSongs = songs;

        // 更新UI
        ((android.app.Activity) mContext).runOnUiThread(() -> {
            mView.hideLoading();

            if (finalPlayUrl.isEmpty()) {
                // 如果URL为空，显示歌曲信息但提示无法播放
                mView.showSongs(finalSongs);
                mView.showToast("歌曲 '" + finalSongTitle + "' 暂无播放链接，请点击随机按钮重试");
            } else {
                mView.showSongs(finalSongs);
                mView.showToast("获取到歌曲: " + finalSongTitle + " - " + finalSongArtist);
            }
        });
    }

    /**
     * 从多个可能的字段名中获取值
     */
    private String getFieldValue(JSONObject data, String[] fieldNames, String defaultValue) {
        for (String fieldName : fieldNames) {
            if (data.has(fieldName)) {
                String value = data.optString(fieldName, "").trim();
                if (!value.isEmpty() && !"null".equals(value)) {
                    return value;
                }
            }
        }
        return defaultValue;
    }

    /**
     * 获取酷狗音乐的真实播放链接
     */
    private void getKugouPlayUrl(String hash, PlayUrlCallback callback) {
        if (hash == null || hash.isEmpty()) {
            callback.onFailure("无效的歌曲hash");
            return;
        }

        String apiUrl = "https://wwwapi.kugou.com/yy/index.php?r=play/getdata&hash=" + hash + "&mid=123456";

        Request request = new Request.Builder()
                .url(apiUrl)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.onFailure("网络请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseData = response.body().string();
                        JSONObject json = new JSONObject(responseData);

                        if (json.getInt("status") == 1) {
                            JSONObject data = json.getJSONObject("data");
                            String playUrl = data.getString("play_url");

                            if (playUrl != null && !playUrl.isEmpty()) {
                                callback.onSuccess(playUrl);
                            } else {
                                callback.onFailure("未找到播放链接");
                            }
                        } else {
                            callback.onFailure("API返回错误: " + json.optString("error", "未知错误"));
                        }
                    } catch (Exception e) {
                        callback.onFailure("解析播放链接失败: " + e.getMessage());
                    }
                } else {
                    callback.onFailure("HTTP错误: " + response.code());
                }
            }
        });
    }

    interface PlayUrlCallback {
        void onSuccess(String playUrl);
        void onFailure(String error);
    }


}